package com.easyfun.healthmagicbox;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.HealthThreadPool;
import com.easyfun.healthmagicbox.comm.ShareRetrieveInvitedCodeTask;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.PersonProfile;
import com.easyfun.healthmagicbox.pojo.User;
import com.easyfun.healthmagicbox.pojo.UserToPersons;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.util.PersonProfileCache;
import com.easyfun.healthmagicbox.widget.DialogBuilder;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;

public class SharePageActivity extends BaseActivity implements DatabaseAccess {

	Button inviteButton = null;
	Button inviteCodeButton = null;

	private TextView txtShareCode;
	ListView sharelistview;
	private ArrayAdapter<String> mInputAdapter;
	
	private final static String LOG_TAG = SharePageActivity.class.getSimpleName();
	protected static final String TAG = SharePageActivity.class.getSimpleName();
	@Override
	public DatabaseHelper getHelper(Context context) {
		return DatabaseAccessImplementation.getInstance().getHelper(context);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sharepage);
		//should after set Content
		addbackButton(this);
		checkPersonId();
		inviteButton = (Button) findViewById(R.id.btn_invite);
		inviteCodeButton = (Button) findViewById(R.id.btn_inviteCode);
		txtShareCode = (TextView) findViewById(R.id.txt_inviteCode);

		sharelistview = (ListView) findViewById(R.id.sharelistview1);
		//---------------------------------------------------
		mInputAdapter = new ArrayAdapter<String>(this,
				R.layout.one_lastinputlistitem,
				R.id.lastinputtitem_info,
				new ArrayList<String>());
		updateshareList(mInputAdapter);

		mInputAdapter.setNotifyOnChange(true);
		sharelistview.setAdapter(mInputAdapter);
		
		sharelistview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				//only sharee can edit share list
				boolean canEdit = false;
				Dao<PersonProfile, Integer> utop;
				try {
					Dao<User, Integer> userDao = getHelper(SharePageActivity.this)
							.getUserDao();
					List<User> users = userDao.queryForEq("personID", SharePageActivity.this.m_personid);
					if (users.size() == 1)
					{
						if (users.get(0).getUsername().equals(
								PersonProfileCache.getInstance(SharePageActivity.this).getUsername(SharePageActivity.this)))
						{
							canEdit = true;
						}
					}
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					return;
				}
				
				if (!canEdit)
				{
					return;
				}
				
				final String shareusername = mInputAdapter.getItem(position);
				new DialogBuilder(SharePageActivity.this)
				.setTitle("提示")
				.setMessage("删除此分享?")
				.setButtons("确定","取消", new DialogBuilder.OnDialogButtonClickListener() {
					@Override
					public void onDialogButtonClick(Context context, DialogBuilder builder, Dialog dialog, int dialogId, int which) {
						if (which == BUTTON_LEFT)
						{
							try {
								Dao<PersonProfile, Integer> utop = getHelper(SharePageActivity.this)
									.getPersonProfileDao();
								List<PersonProfile> pp = utop.queryForEq("personID", m_personid);
								String newsharelist = "";
								if (pp.size() == 1)
								{
									String sharelist = pp.get(0).getSharelist();
									if ((sharelist!=null ) &&(sharelist.length()>0))
									{
										String[] sharee = sharelist.split("\\ ");
										if (sharee.length>1)
										{						
											for(String shareone:sharee)
											{
												if (shareone.trim().equals(shareusername.trim()))
												{
													continue;
												}else
												{
													newsharelist = newsharelist + shareone + " ";
												}
											}
										}
									}
									//update 
									pp.get(0).setSharelist(newsharelist);
									utop.update(pp.get(0));
								}else
								{
									
								}
							} catch (SQLException e) {
								e.printStackTrace();
								Toast.makeText(getApplicationContext(),
										"更新分享列表失败2dui ",
										Toast.LENGTH_SHORT).show();
							}						
						}						
					}
				}).create().show(); 
			}
		});
		
		/*
		Dao<UserToPersons, Integer> utopDao;
		try {
			utopDao = getHelper(this).getUserToPersonsDao();

			List<UserToPersons>r = utopDao.queryBuilder().where().eq("personID", m_personid)
					.and().eq("username", PersonProfileCache.getInstance(SharePageActivity.this)
										  .getUsername(SharePageActivity.this)).query();
			if (r.size() == 1)
			{
				txtShareCode.setText("分享码：" + String.valueOf(r.get(0).getInvitecode()));
				inviteCodeButton.setEnabled(false);
			}else
			{
				txtShareCode.setText("无");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		*/
		
		inviteButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try{
					String inviteCode = txtShareCode.getText().toString();
					OnekeyShare oks = new OnekeyShare();
	
					// 分享时Notification的图标和文字
					oks.setNotification(R.drawable.ic_launcher,
							SharePageActivity.this.getString(R.string.app_name));
					// address是接收人地址，仅在信息和邮件使用
					//oks.setAddress("12345678901");
					// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
					oks.setTitle(SharePageActivity.this.getString(R.string.app_name));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					//oks.setTitleUrl("http://sharesdk.cn");
					// text是分享文本，所有平台都需要这个字段
					oks.setText("您要下载健康宝盒，输入分享码："+inviteCode+" 就可以分享他/她的健康数据了！");
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					//oks.setImagePath(MainActivity.TEST_IMAGE);
					// imageUrl是图片的网络路径，新浪微博、人人网、QQ空间、
					// 微信的两个平台、Linked-In支持此字段
					oks.setImageUrl("http://www.kangbox.cn/cakephp/images/hblogo72.png");
					// url仅在微信（包括好友和朋友圈）中使用
					oks.setUrl("http://www.kangbox.cn/cakephp/download.php");
					// appPath是待分享应用程序的本地路劲，仅在微信中使用
					//oks.setAppPath(MainActivity.TEST_IMAGE);
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					//oks.setComment(getContext().getString(R.string.share));
					// site是分享此内容的网站名称，仅在QQ空间使用
					//oks.setSite(context.getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					//oks.setSiteUrl("http://sharesdk.cn");
					// venueName是分享社区名称，仅在Foursquare使用
					//oks.setVenueName("Southeast in China");
					// venueDescription是分享社区描述，仅在Foursquare使用
					//oks.setVenueDescription("This is a beautiful place!");
					// latitude是维度数据，仅在新浪微博、腾讯微博和Foursquare使用
					//oks.setLatitude(23.122619f);
					// longitude是经度数据，仅在新浪微博、腾讯微博和Foursquare使用
					//oks.setLongitude(113.372338f);
					// 是否直接分享（true则直接分享）
					oks.setSilent(true);
					// 指定分享平台，和slient一起使用可以直接分享到指定的平台
					//if (platform != null) {
					//        oks.setPlatform(platform);
					//}
					// 去除注释可通过OneKeyShareCallback来捕获快捷分享的处理结果
					// oks.setCallback(new OneKeyShareCallback());
					//通过OneKeyShareCallback来修改不同平台分享的内容
					//oks.setShareContentCustomizeCallback(
					//new ShareContentCustomizeDemo());
	
					oks.show(SharePageActivity.this);
				}catch (Exception e)
				{
					e.printStackTrace();
					Log.e(TAG,e.toString());
				}
				/* */	
			}
		});
		//----------------------
		inviteCodeButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String inviteCode = subInviteCode();
				if (inviteCode.length()==0)
				{

					Toast.makeText(SharePageActivity.this,
							"获取分享码失败！",
							Toast.LENGTH_SHORT).show();
					return;
				}
				txtShareCode.setText("分享码："+inviteCode);
				Toast.makeText(SharePageActivity.this,
						"获取分享码成功！请发送邀请",
						Toast.LENGTH_SHORT).show();
				inviteCodeButton.setEnabled(false);
			}
		});
	}

	private void updateshareList(ArrayAdapter<String> inputAdapter) {
		inputAdapter.clear();
		try {
			Dao<PersonProfile, Integer> utop = getHelper(SharePageActivity.this)
				.getPersonProfileDao();
			
			List<PersonProfile> pp = utop.queryForEq("personID", m_personid);
			if (pp.size() == 1)
			{
				String sharelist = pp.get(0).getSharelist();
				if ((sharelist!=null ) &&(sharelist.length()>0))
				{
					String[] sharee = sharelist.split("\\ ");
					if (sharee.length>1)
					{						
						for(String shareone:sharee)
						{
							if (shareone.length()>1)
								inputAdapter.add(shareone);
						}

						/*
						txtSharelist.setText("分享给："+sharelist);
						seperator_share.setVisibility(View.VISIBLE);
						txtSharelist.setVisibility(View.VISIBLE);
						RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
								FrameLayout.LayoutParams.MATCH_PARENT,
								FrameLayout.LayoutParams.WRAP_CONTENT);
						params.addRule(RelativeLayout.BELOW, R.id.txtSharelist);			
						seperator2.setLayoutParams(params);
						*/
						return;
					}
				}
			}
			/*
			seperator_share.setVisibility(View.GONE);
			txtSharelist.setVisibility(View.GONE);
			RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
					FrameLayout.LayoutParams.MATCH_PARENT,
					FrameLayout.LayoutParams.WRAP_CONTENT);
			params.addRule(RelativeLayout.BELOW, R.id.titleline);			
			seperator2.setLayoutParams(params);
			*/
		} catch (SQLException e) {
			e.printStackTrace();
			Toast.makeText(getApplicationContext(),
					"更新分享列表失败2dui ",
					Toast.LENGTH_SHORT).show();
		}
		if (inputAdapter.isEmpty())
		{
			inputAdapter.add("没有分享数据给别人。");
		}
	}
	
	private String subInviteCode()
	{
		String invitecode="";
		BasicCommCallback ccb = new BasicCommCallback();
		ShareRetrieveInvitedCodeTask task = new ShareRetrieveInvitedCodeTask(
				 SharePageActivity.this,ccb
				 , invitecode, m_personid);       
		HealthThreadPool.getInstance().execute(task);
		int i=0;
		while ((ccb.getCommResult(null, null)==ServerResponseCode.WAITING)
				&& (i<50))
		{
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			i++;
		}
		return ccb.getResultValue();
	}
	
	/*
	private String invite()
	{
		PersonProfile pp = new PersonProfile();
		m_personid = PersonProfileCache.generatePersonID(this);
		pp.setPersonID(m_personid);
		
		pp.setName(""); //txtName.getText().toString()
		pp.setTitle(""); //getAllTitle()[mTitle]
		pp.setImageFileName(ConstantData.DEFAULT_HEAD_ICON_MALE);
		
						
		// get our dao
		try {
			
			Dao<PersonProfile, Integer> profileDao = getHelper(this).getPersonProfileDao();
			
			
			pp.setManualinput(ConstantData.ManualInputYes);
			profileDao.create(pp);
		
			PersonProfileUploadTask task = new PersonProfileUploadTask(getBaseContext(), m_personid, 
						new BasicCommCallback());
			HealthThreadPool.getInstance().execute(task);
						
			//save list
			Dao<UserToPersons, Integer> utopDao = getHelper(this).getUserToPersonsDao();
			List<UserToPersons> r = utopDao.queryBuilder().where().eq("personID", pp.getPersonID())
							.and().eq("username", PersonProfileCache.getInstance(SharePageActivity.this)
												  .getUsername(SharePageActivity.this)).query();
			UserToPersons up;
			if (r.size() == 0)
			{
				up = new UserToPersons();
				up.setPersonID(pp.getPersonID());
				up.setUsername(PersonProfileCache.getInstance(SharePageActivity.this).getUsername(SharePageActivity.this));
				up.setInvitecode(-1);
				up.setServerID("zzz");
				utopDao.create(up);
			}else
			{
				up = r.get(0);
				up.setInvitecode(-1);
			}
			CommCallback ccb = new BasicCommCallback();
			
			UserToPersonsUpTask task2 = new UserToPersonsUpTask(
					PersonProfileCache.getInstance(SharePageActivity.this).getUsername(SharePageActivity.this), 
					m_personid, 
					-1,"",
					this,ccb
					);
			HealthThreadPool.getInstance().execute(task2);
			int i=0;
			while ((ccb.getCommResult(null, null)==ServerResponseCode.WAITING)
					&& (i<50))
			{
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				i++;
			}
			
			if (ccb.getCommResult(null, null)==ServerResponseCode.SUCCESS)
			{
				r = utopDao.queryBuilder().where().eq("personID", pp.getPersonID())
						.and().eq("username", PersonProfileCache.getInstance(SharePageActivity.this)
											  .getUsername(SharePageActivity.this)).query();
				if (r.size() == 1)
				{
					return String.valueOf(r.get(0).getInvitecode());
				}
			}
			
			
			Log.i(LOG_TAG , "created invited code.");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}
		return "";
	}
	*/
	
	/*
	private String getImageFileName(String m_personid2)
	{
		return m_personid2+".png";
	}
	*/
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if (hasFocus) {
			// picture has updated.
			
			updateshareList(mInputAdapter);
			
			mInputAdapter.notifyDataSetChanged();
		}
	}
}
